<?php
namespace classlib;
class web {
	//定义ajax请求的请求头判断
	const AJAXHTTP = 'HTTP_X_REQUESTED_WITH';
	/**
	 * 设置浏览器缓存，用于缓存一些小页面
	 * @param number $expire
	 */
	public static function cached($expire = 86400, $cookie = false) {
		if ($expire < 1) { //不缓存页面资料信息
			header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
			header('Cache-Control: private, no-store, no-cache, must-revalidate');
			header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);
			header('Pragma: no-cache');
			return;
		}
		$nowtime = \classlib\core\config::$nowtime;
		//普通的强制浏览器缓存住页面
		if (!$cookie && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
			$stime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
			if ($nowtime - $stime < $expire) {
				header('HTTP/1.1 304 Not Modified');
				exit;
			}
		}
		$etag    = ($cookie)? md5(json_encode($_COOKIE)):'';
		//判断如果cookie更新 页面浏览器缓存中的页面重新刷新
		if ($etag && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
			$stime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
			if ($nowtime - $stime < $expire && $etag == $_SERVER['HTTP_IF_NONE_MATCH']) {
				header('HTTP/1.1 304 Not Modified');
				exit;
			}
		}
		header('Cache-Control: max-age='.$expire);
		header('Last-Modified: '.gmdate('r'). 'GMT');
		header('Expires: '.gmdate('r', time() +  $expire). 'GMT');
		if ($etag) {
			header('Etag: ' . $etag);
		}
	}
	
    /**
     * 设置生成一个随机的验证token
     * @param number $expire
     * @return string
     */
    public static function addcsrf($expire=3600) {
    	$rstr = 'CSRFTKS-'.\classlib\core\rand_str(8);
    	\classlib\core\model::$cacher->set($rstr, 1, $expire);
    	return $rstr;
    }
    
    /**
     * 验证表单提交的一个循环冗余码是否正确
     * @param string $rstr
     * @return bool
     */
    public static function chkcsrf() {
    	$cache = \classlib\core\model::$cacher;
    	//没开启无需验证
    	if ($cache instanceof \classlib\cache\cache_nocache) {
    		return true;
    	}
    	$rstr = \classlib\input::get_post('req_CSRFTOKEN');
    	if (!$rstr) {
    		$rstr = \classlib\input::get_post('csrf');
    	}
    	if ($cache->get($rstr)) {
    		$cache->delete($rstr);
    		return true;
    	}
    	return false;
    }
}
